# -*- coding: utf-8 -*-
import re
import os
import requests
import json
import re
from pyquery import PyQuery as pq


def findPart(regex, text, name):
    a = u"这是个中文"
    b = re.compile(u"[\u4e00-\u9fa5]{1,2}")
    # res = b.findall(text)
    res = re.findall(regex, text)
    if res:
        print("There are %d %s parts:\n" % (len(res), name))
    for r in res:
        print("\t", r.encode("utf8"))


# text = "#who#helloworld#a中文x#".encode('utf-8').decode('utf-8')
# usample = text.encode('utf8')
# findPart(u"[\u4e00-\u9fa5]+", text, "unicode chinese")
#

# print(bf_page('#jq_odds_home_1').text())
pattern = re.compile(r'\d{1,2}:\d{1,2}')
jq_price_home = 'jq_price_home_'  # 必发价位胜
jq_index_home = 'jq_index_home_'  # 必发指数胜
jq_odds_home = 'jq_odds_home_'  # 百家欧赔胜
jq_price_draw = 'jq_price_draw_'  # 必发价位平
jq_index_draw = 'jq_index_draw_'  # 必发指数平
jq_odds_draw = 'jq_odds_draw_'  # 百家欧赔平
jq_price_away = 'jq_price_away_'  # 必发价位负
jq_index_away = 'jq_index_away_'  # 必发指数负
jq_odds_away = 'jq_odds_away_'  # 百家欧赔负
jq_homeTeam = 'jq_homeTeam_'  # 主场
jq_awayTeam = 'jq_awayTeam_'  # 客场
md_ks_time = '.md_ks_time'  # 开赛时间
liansai_class = '.c_dgreen'  # 联赛名的class


def getData(start, end):
    file_out = open("sina_bifa.csv", 'a+', encoding='utf-8')
    for issue in range(start, end):
        # 'http://live.aicai.com/pages/bf/sfc.shtml?issue=13015'
        data_url = "http://live.aicai.com/jsbf/timelyscore!dynamicBfDataFromPage.htm?lotteryType=sfc&issue=%d" % issue
        response = requests.get(data_url)
        # print(response.text)
        data = json.loads(response.text)
        # print(data)
        if data['status'] == 'fail':
            print(data_url)
            # print(data)
            continue
        if 'result' not in data or 'bf_page' not in data['result']:
            print(data_url)
            # print(data)
            continue
        bf_page = pq(data['result']['bf_page'])
        # print(bf_page.html())
        last_score = bf_page('span')
        index = 0
        for i in range(last_score.size()):
            score = last_score.eq(i)
            # print(score)
            match = pattern.match(score.text())
            if match:
                # print(match.group())
                index += 1
                score_num = match.group()
                price_home = bf_page('#%s%d' % (jq_price_home, index)).text()
                price_draw = bf_page('#%s%d' % (jq_price_draw, index)).text()
                price_away = bf_page('#%s%d' % (jq_price_away, index)).text()
                index_home = bf_page('#%s%d' % (jq_index_home, index)).text()
                index_draw = bf_page('#%s%d' % (jq_index_draw, index)).text()
                index_away = bf_page('#%s%d' % (jq_index_away, index)).text()
                odds_home = bf_page('#%s%d' % (jq_odds_home, index)).text()
                odds_draw = bf_page('#%s%d' % (jq_odds_draw, index)).text()
                odds_away = bf_page('#%s%d' % (jq_odds_away, index)).text()

                start_time = bf_page(md_ks_time).eq(index - 1).text().replace('开赛时间: ', '')
                liansai_name = bf_page(liansai_class).eq(index - 1).text()
                home_team = bf_page('#%s%d' % (jq_homeTeam, index)).text()
                away_team = bf_page('#%s%d' % (jq_awayTeam, index)).text()

                record = ("%s,%d,%d,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s\n"
                          % (
                          start_time, issue, index, liansai_name, home_team, away_team, score_num,
                          price_home, index_home, odds_home,
                          price_draw, index_draw, odds_draw,
                          price_away, index_away, odds_away))
                file_out.write(record)
                print(record)
    file_out.close()

if __name__ == '__main__':
    # 2014年
    # getData(14001, 14189)
    # 2015年
    # getData(15001, 15199)
    # 2016年
    # getData(16001, 16199)
    # 2017年
    getData(17001, 17089)
    '''
    文件格式
    开赛时间，足彩期号，场次，联赛，主场，客场，比分，必发胜,平,负,必发指数胜,平,负,百家欧赔胜,平,负
    '''
